#include "DB.h"
#include <QDebug>
#include <QtSql/QSqlQuery>
#include <QSettings>

DB::DB()
{
    if (QSqlDatabase::contains("qt_sql_default_connection")){
        db = QSqlDatabase::database("qt_sql_default_connection");
    }else{
        db = QSqlDatabase::addDatabase("QMYSQL"); //添加数据库驱动
    }
    /*
    db.setHostName("127.0.0.1");
    db.setPort(3336);
    db.setDatabaseName("TD_OA");
    db.setUserName("root");
    db.setPassword("myoa888");
    */
    //DBSetting dbSetting = DB::getDbSetting();

    QSettings settings("data.ini", QSettings::IniFormat);
//    DBSetting dbSetting;
//    m_server = settings.value("data/server","localhost").toString();
//    dbSetting.port = settings.value("data/port","3336").toString();
//    dbSetting.userName = settings.value("data/userName","root").toString();
//    dbSetting.pwd = settings.value("data/pwd","myoa888").toString();
//    dbSetting.database = settings.value("data/database","td_oa").toString();

    db.setHostName(settings.value("data/server","localhost").toString());
    db.setPort(settings.value("data/port","3336").toInt());
    db.setDatabaseName(settings.value("data/database","dothing").toString());
    db.setUserName(settings.value("data/userName","root").toString());
    db.setPassword(settings.value("data/pwd","myoa888").toString());

    if( !db.open() )
    {
        qDebug()<<"this,warning,failure";
    }
    else
    {
        qDebug()<<"this,ok,success";
    }
}

DB::~DB(){
    if(db.isOpen())
        db.close();
}

DB* DB::getInstance()
{
    static DB db11;
    return &db11;
}
QSqlQuery DB::getQuery()
{
    if(db.isValid()){
        return QSqlQuery(db);
    }else{
        qDebug()<<"db is invalid";
        return QSqlQuery();
    }
}

void DB::setDbSetting(){
    QSettings settings("data.ini", QSettings::IniFormat);
    //DBSetting dbSetting;
//    m_server = settings.value("data/server","localhost").toString();
//    dbSetting.port = settings.value("data/port","3336").toString();
//    dbSetting.userName = settings.value("data/userName","root").toString();
//    dbSetting.pwd = settings.value("data/pwd","myoa888").toString();
//    dbSetting.database = settings.value("data/database","td_oa").toString();
}

//DBSetting DB::getDbSetting(){
//    return dbSetting;
//}



